package by.grsu.vashchilo.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.vashchilo.dao.impl.AbstractDao;
import by.grsu.vashchilo.entity.Ticket;
import by.grsu.vashchilo.table.TicketTable;


public class TicketDao extends AbstractDao<TicketTable, Ticket> {

	public TicketDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	public List<Ticket> searchId(Long ID) {
		final TicketTable ticketTable = deserializeFromXml();
		List<Ticket> listTicket = new ArrayList<Ticket>();
		for (Ticket b : ticketTable.getRows()) {
			if (b.getID().equals(ID)) {
				listTicket.add(b);
			}
		}
		return listTicket;
	}

	public List<Ticket> searchByTripId(Long s) {
		final TicketTable ticketTable = deserializeFromXml();
		List<Ticket> result = new ArrayList<Ticket>();
		for (Ticket b : ticketTable.getRows()) {
			if (b.getTripID().equals(s)) {
				result.add(b);
			}
		}
		return result;
	}

	public List<Ticket> searchBySeat(Long d) {
		final TicketTable ticketTable = deserializeFromXml();
		List<Ticket> listTicket = new ArrayList<Ticket>();
		for (Ticket b : ticketTable.getRows()) {
			if (b.getSeat().equals(d)) {
				listTicket.add(b);
			}
		}
		return listTicket;
	}

	public void saveNew(Ticket newTicket) {
		newTicket.setId(getNextId());
		final TicketTable ticketTable = deserializeFromXml();
		ticketTable.getRows().add(newTicket);
		serializeToXml(ticketTable);

	}

	@Override
	public void update(Ticket entity) {
		final TicketTable ticketTable = deserializeFromXml();
		for (Ticket b : ticketTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				b.setID(entity.getID());
				b.setTripID(entity.getTripID());
				b.setSeat(entity.getSeat());
				}
		}
		serializeToXml(ticketTable);
	}

	@Override
	public Ticket get(Serializable id) {
		final TicketTable ticketTable = deserializeFromXml();
		for (Ticket b : ticketTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<Ticket> getAll() {
		TicketTable ticketTable = deserializeFromXml();
		return ticketTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final TicketTable ticketTable = deserializeFromXml();
		Ticket toBeDeletedTicket = null;
		for (Ticket b : ticketTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedTicket = b;
			}
		}
		ticketTable.getRows().remove(toBeDeletedTicket);
		serializeToXml(ticketTable);
	}

	@Override
	protected Class<TicketTable> getTableClass() {
		return TicketTable.class;
	}

}
